<template>
  <div class="upload-img" :style="{'width': listWidth, 'height': uploadImgHeight}" :class="{'upload-bg': bg}">
    <div v-for="(file, index) in files" :key="file.id">
      <div class="file-img t-center">
        <img
          ref="img"
          v-if="file.blob"
          :src="file.blob"
          @load="computedHeight"
          :width="ImgWidth"
          :style="{'margin-top': `${imgTop}px`}"
          :height="ImgHeight"/>
        <img
          ref="img"
          v-if="file.reurl"
          @load="computedHeight"
          :src="file.reurl"
          :style="{'margin-top': `${imgTop}px`}"
          :width="ImgWidth"
          :height="ImgHeight"/>
        <div v-if="!file.success" class="file-progress" :style="{width: file.progress + '%'}"></div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'zz-upload-img',
    filters: {
      type (value) {
        const fType = value.split('.')
        return fType[1]
      }
    },
    data () {
      return {
        ImgWidth: '50px',
        ImgHeight: 'auth',
        imgTop: 0,
        bg: false
      }
    },
    props: {
      listWidth: {
        type: String,
        default: '50px'
      },
      uploadImgHeight: {
        type: String,
        default: '100%'
      },
      listHeight: {
        type: String,
        default: '50px'
      },
      files: {
        type: Array
      }
    },
    mounted () {
      this.ImgWidth = this.listWidth
    },
    methods: {
      computedHeight () {
        this.bg = true
        let {naturalHeight, naturalWidth} = this.$refs.img[0]
        if (naturalHeight > naturalWidth) {
          this.ImgWidth = 'auth'
          this.ImgHeight = this.listHeight
        }
        let clientHeight = this.$refs.img[0].clientHeight
        let listHeight = Number.parseInt(this.listHeight)
        if (clientHeight < listHeight && clientHeight !== 0) {
          this.imgTop = (listHeight - clientHeight) / 2
        }
      },
      remove (file) {
        this.bg = false
        this.$store.commit('reomveFiles', file)
      }
    }
  }
</script>

<style lang="scss">
  .upload-img{
    position: absolute;
    left: -1px;
    top: 0;
    padding-left: 1px;
  }
  .upload-bg{
    background: #fff;
  }
</style>
